import { defineStore } from "pinia";
import { loginApi, getUserInfo, logout as logoutApi } from "@/api/auth";
import axios from "axios";

export const useAuthStore = defineStore('auth', {
  state: () => ({
    userInfo: null,   // 登录用户对象信息
    accessToken: '',  // 登录token
    refreshToken: '', // 刷新token
    isLogin: false,   // 是否登录
    routes: []        // 用户动态路由信息(访问权限)
  }),
  getters: {
    username: (state) => state.userInfo?.username || '',
    isAuthenticated: (state) => state.isLogin && !!state.accessToken
  },
  actions: {
    // 用户登录
    async login(data) {
      try {
        const res = await loginApi(data);
        const { accessToken, refreshToken } = res.data;

        this.accessToken = accessToken;
        this.refreshToken = refreshToken;
        this.isLogin = true;

        // 登录成功后获取用户信息
        await this.fetchUserInfo();

        return true;
      } catch (err) {
        console.error('登录失败', err);
        return false;
      }
    },

    // 获取用户信息 + 可访问路由
    async fetchUserInfo() {
      if (!this.accessToken) return null;
      try {
        const res = await getUserInfo();
        const { user, routes } = res.data;
        this.userInfo = user;
        this.routes = routes;
        return res.data;
      } catch (err) {
        console.error('获取用户信息失败', err);
        this.logout();
        return null;
      }
    },

    // 登出
    async logout() {
      try {
        await logoutApi();
      } catch (e) {
        console.warn("后端退出接口调用失败，可忽略", e);
      }
      this.accessToken = '';
      this.refreshToken = '';
      this.userInfo = null;
      this.routes = [];
      this.isLogin = false;
    },

    // 刷新 token
    async refreshTokenAction() {
      try {
        const res = await axios.post('/api/refresh-token', { token: this.refreshToken });
        const { accessToken } = res.data;
        this.accessToken = accessToken;
        axios.defaults.headers.common['Authorization'] = `Bearer ${accessToken}`;
        return accessToken;
      } catch (err) {
        console.error('刷新 token 失败', err);
        this.logout();
        return null;
      }
    }
  },
  persist: {
    key: 'auth-store',
    storage: localStorage,
    paths: ['accessToken', 'refreshToken', 'userInfo', 'routes', 'isLogin']
  }
});
